package pers.cz.transform;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.LoaderClassPath;

import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @program: postgirl-collection-client
 * @description: HttpTransformer
 * @author: Cheng Zhi
 * @create: 2022-03-02 19:43
 **/
public class HttpTransformer implements ITransformer{

    private static final String CLASS_NAME = "org.springframework.web.servlet.DispatcherServlet";
    private static final String METHOD_NAME = "doService";
    @Override
    public void doInert(String... params) {

    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        String finalClassName = className.replace("/", ".");
        if (finalClassName.equals(CLASS_NAME)) {
            // 动态修改代码
            try {
                ClassPool classPool = new ClassPool(true);
                classPool.insertClassPath(new LoaderClassPath(loader));
                // 获取目标类
                CtClass ctClass = classPool.get(CLASS_NAME);
                // 获取要监听的方法
                CtMethod beginMethod = ctClass.getDeclaredMethod(METHOD_NAME);
                String beginSrc = "{pers.cz.mock.HttpRequestUpdate.begin($1,$2);}";
                String endSrc = "{pers.cz.mock.HttpRequestUpdate.end($1,$2);}";
                beginMethod.insertBefore(beginSrc);
                beginMethod.insertAfter(endSrc);

                return ctClass.toBytecode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }
}
